/** create by liuhua at 2017年5月19日 下午2:07:11 **/
package com.star.truffle.module.user.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.star.truffle.core.security.StarSecurityProperties;
import com.star.truffle.core.security.StarSecurityProperties.ApiLogin;
import com.star.truffle.core.security.dto.StarUserInfo;

@Service
public class CoachUserDetailsService implements UserDetailsService {

  @Autowired
  private StarSecurityProperties securityProperties;
  @Autowired
  private PasswordEncoder passwordEncoder;
  
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    ApiLogin apiLogin = securityProperties.getApiLogins().stream().filter(al -> al.getUri().equals("/api/coach/login")).findAny().orElse(null);
    if(null != apiLogin) {
      List<SimpleGrantedAuthority> auths = new ArrayList<>();
      if(null != apiLogin.getRoles() && ! apiLogin.getRoles().isEmpty()) {
        auths = apiLogin.getRoles().stream().map(roleName -> {
          return new SimpleGrantedAuthority("ROLE_" + roleName.toUpperCase());
        }).collect(Collectors.toList());
      }
      StarUserInfo starUserInfo = new StarUserInfo("coach", passwordEncoder.encode("111"), auths);
      return starUserInfo;
    }else {
      return null;
    }
  }
}
